﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Amazon_Book_Search.AmazonService;

namespace Amazon_Book_Search.Models
{
    public class ItemWrapper
    {
        private List<AmazonItem> items;
        public List<AmazonItem> Items
        {
            get { return items; }
            set { items = value; }
        }

        private int resultCount;
        public int ResultCount
        {
            get { return resultCount; }
            set { resultCount = value; }
        }

        private int pageCount;
        public int PageCount
        {
            get { return pageCount; }
            set { pageCount = value; }
        }

        public static ItemWrapper getItemsFromAmazon(String title, int pageNum)
        {
            List<AmazonItem> items = new List<AmazonItem>();

            // prepare an ItemSearch request
            ItemSearchRequest request = new ItemSearchRequest();
            request.SearchIndex = "All";
            request.Condition = Condition.All;
            request.MerchantId = "All";
            request.Keywords = title;
            
            request.ResponseGroup = new string[] { "Medium", "Images", "Reviews", "OfferSummary" };
            request.ItemPage = pageNum.ToString();

            ItemSearchResponse res = AmazonDAO.searchItems(request);
            if (res.Items[0].Item != null)
            {
                foreach (var item in res.Items[0].Item)
                {
                    string url = item.DetailPageURL;
                    if (url.EndsWith("null"))
                    {
                        url = url.Remove(url.Length - 4);
                    }


                    items.Add(new AmazonItem
                    {
                        Image = item.MediumImage,
                        Price = item.OfferSummary.LowestNewPrice.FormattedPrice,
                        Review = item.EditorialReviews
                    });
                }
            }

            return new ItemWrapper { items = items,
                                     pageCount = Convert.ToInt32(res.Items[0].TotalPages),
                                     resultCount = Convert.ToInt32(res.Items[0].TotalResults) };
        }

    }
}